package com.handler;

import com.message.ChatReqMessage;
import com.message.resp.ChatResp;
import com.session.ChatServerContext;
import com.session.ChatServerContextFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Objects;

/**
 * 转发聊天消息的处理器
 */
@ChannelHandler.Sharable
public class ChatDispatchHandler extends SimpleChannelInboundHandler<ChatReqMessage> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatReqMessage msg) throws Exception {

        ChatServerContext chatServerContext = ChatServerContextFactory.getInstance();
//                                          通过当前连接的 channel 获取到当前登录用户的 userName
        String currentLoginUserName = chatServerContext.getUserNameByChannel(ctx.channel());

//                                          找出这条消息的接收者
        Channel toUserChannel = chatServerContext.getChannelByUserName(msg.getToUserName());

        if (Objects.isNull(toUserChannel)) {
//                                            如果接收者未连接到服务器，就提示一个为连接的消息
            ctx.writeAndFlush(ChatResp.receiverNotOnLine(msg.getToUserName()));
        } else {
//          将消息转发给消息的接收者
            toUserChannel.writeAndFlush(ChatResp.sendSuccess(currentLoginUserName, msg.getChatContent()));
//          告诉消息发送者，消息已经成功转发
            ctx.writeAndFlush(ChatResp.sendSuccess());
        }

        ctx.fireChannelRead(msg);
    }
}
